import sys
import math
num_items = 6095
if __name__ == '__main__':
    if len(sys.argv) < 5:
        print 'usage: <itemf1> <itemf2> <itemfout> <offset1> [mode]'
        sys.exit(1)
    if len(sys.argv) > 5:
        mode = int( sys.argv[5] )
    else:
        mode = 0

    abase = int( sys.argv[4] )
    fa = open( sys.argv[1], 'r' )
    fb = open( sys.argv[2], 'r' )
    fo = open( sys.argv[3], 'w' )
    for la in fa:
        arra = la.split()
        arrb = fb.readline().split()
        idx = []
        val = []
        for it in arra[1:len(arra)]:
            k,v = it.split(':')
            k,v = int(k), float(v)
            val.append( v )
            idx.append( k )
            assert k >= num_items and k < abase + num_items

        for it in arrb[1:len(arrb)]:
            k,v = it.split(':')
            k,v = int(k), float(v)
            assert k >= num_items
            k += abase
            val.append( v )
            idx.append( k )
        
        fo.write( '%d' % len(val) )
        if mode == 0:
            wsum = sum( [ v*v for v in val ] )
            wsum = math.sqrt( wsum )
        else:
            wsum = 1.0

        for i in xrange( len(val) ):
            fo.write( ' %d:%f' % (idx[i], val[i]/wsum) )
        fo.write('\n')
    fo.close()
    fa.close()
    fb.close()
